import { ShellUtil } from "./ShellUtil";
import { Main } from "../Main";

/**
 * 合图工具
 * @author 赵占涛
 */
export class PicMergeUtil {
    static merge(type: "normal" | "ios" | "android", dir: string, plistPng: string, spriteFramePrefix: string, cb: () => void) {
        console.log("merge pic");
        if (Main.TexturePackerVersion == "4.6.3" || type == "android") {
            spriteFramePrefix = "/" + spriteFramePrefix.substr(0, spriteFramePrefix.substr(0, spriteFramePrefix.length - 1).lastIndexOf("/") + 1);
            console.log("spriteFramePrefix", spriteFramePrefix);
        }
        switch (type) {
            case "normal":
                this.mergeToPng(dir, plistPng, spriteFramePrefix, cb)
                break;

            case "ios":
                this.mergeToPvr(dir, plistPng, spriteFramePrefix, cb)
                break;

            case "android":
                this.mergeToEtc(dir, plistPng, spriteFramePrefix, cb)
                break;
        }
    }
    static mergeToPng(dir: string, plistPng: string, spriteFramePrefix: string, cb: () => void) {
        console.log("merge to png")
        ShellUtil.exec(`
        TexturePacker ${dir} --data ${plistPng}.plist --sheet ${plistPng}.png --replace ^=${spriteFramePrefix} --opt RGBA8888 --disable-rotation --padding 0 --shape-padding 2 --border-padding 0 --size-constraints AnySize || exit 1
        `, cb);
    }
    static mergeToPvr(dir: string, plistPng: string, spriteFramePrefix: string, cb: () => void) {
        console.log("merge to pvr")
        ShellUtil.exec(`
        TexturePacker ${dir} --data ${plistPng}.plist --sheet ${plistPng}.pvr.ccz --replace ^=${spriteFramePrefix} --opt PVRTC4 --disable-rotation --padding 0 --shape-padding 2 --border-padding 0 --size-constraints AnySize --content-protection a6bada9636ada74895fa5197eeebd45a --premultiply-alpha || exit 1
        `, cb);
    }
    static mergeToEtc(dir: string, plistPng: string, spriteFramePrefix: string, cb: () => void) {
        let tpCmd = "/Applications/TexturePacker.4.6.3.app/Contents/MacOS/TexturePacker";
        ShellUtil.exec(`
        ${tpCmd} ${dir} --data ${plistPng}.plist --sheet ${plistPng}.png --replace ^=${spriteFramePrefix} --opt RGBA8888 --disable-rotation --padding 0 --shape-padding 2 --border-padding 0 --size-constraints AnySize || exit 1

        ${tpCmd} ${plistPng}.png  --sheet ${plistPng}.pkm  --opt ETC1_A  --disable-rotation --padding 0 --shape-padding 0 --border-padding 0 --extrude 0   --algorithm MaxRects  --size-constraints POT || exit 1
        mv ${plistPng}.pkm ${plistPng}.pkm@alpha
        ${tpCmd} ${plistPng}.png  --sheet ${plistPng}.pkm  --opt ETC1_RGB --disable-rotation  --padding 0 --shape-padding 0 --border-padding 0  --extrude 0   --algorithm MaxRects  --size-constraints POT || exit 1
        rm -rf ${plistPng}.png
        sed -i '' 's/png\<\\/string\>/pkm\<\\/string\>/g' ${plistPng}.plist || exit 1
        `, cb);
    }
}